// 函数：显示登录页面的 Toast 提示
function showLoginToast(message, type = 'info') {
    const toastContainer = document.getElementById('toastContainerLogin');
    if (!toastContainer) return;

    const toastId = 'toast-' + Math.random().toString(36).substr(2, 9);
    const toastHTML = `
        <div id="${toastId}" class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
            <div class="toast-header">
                <strong class="mr-auto ${type === 'error' ? 'text-danger' : (type === 'success' ? 'text-success' : 'text-primary')}">
                    ${type === 'error' ? '登录失败' : (type === 'success' ? '登录成功' : '提示')}
                </strong>
                <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        </div>
    `;
    toastContainer.insertAdjacentHTML('beforeend', toastHTML);
    $('#' + toastId).toast('show').on('hidden.bs.toast', function () {
        $(this).remove(); // Remove toast from DOM after it's hidden
    });
}

document.addEventListener('DOMContentLoaded', function () {
    const loginForm = document.getElementById('loginForm');
    const errorMessageDiv = document.getElementById('errorMessage');

    // 如果用户已登录，则直接跳转
    const existingUser = getCurrentUser();
    const existingToken = getToken();
    if (existingUser && existingToken) {
        console.log('已登录用户:', existingUser);
        if (existingUser.role === 'admin') {
            window.location.href = 'admin.html';
        } else if (existingUser.role === 'student') {
            window.location.href = 'student.html';
        }
        return;
    }

    if (loginForm) {
        loginForm.addEventListener('submit', async function (event) {
            event.preventDefault();
            errorMessageDiv.textContent = ''; // 清除之前的错误信息

            const usernameInput = document.getElementById('username');
            const passwordInput = document.getElementById('password');
            const roleSelect = document.getElementById('role');

            const username = usernameInput.value.trim();
            const password = passwordInput.value.trim();
            const role = roleSelect.value;

            if (!username || !password) {
                errorMessageDiv.textContent = '用户名和密码不能为空。';
                showLoginToast('用户名和密码不能为空。', 'error');
                return;
            }

            // 添加登录按钮加载状态
            const loginButton = loginForm.querySelector('button[type="submit"]');
            const originalButtonText = loginButton.innerHTML;
            loginButton.disabled = true;
            loginButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 正在登录...';

            try {
                const response = await fetch(`${API_BASE_URL}/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password, role })
                });

                const data = await response.json();
                console.log('登录响应:', data);

                if (response.ok && data.token) {
                    // 存储 token
                    storeToken(data.token);
                    
                    // 存储用户信息
                    const userInfo = {
                        username: data.username,
                        name: data.name,
                        role: data.role.toLowerCase(), // 确保角色是小写的
                        authorities: data.authorities || []
                    };
                    console.log('存储用户信息:', userInfo);
                    setCurrentUser(userInfo);

                    showLoginToast('登录成功！正在跳转...', 'success');
                    
                    // 延迟一小段时间让toast显示出来
                    setTimeout(() => {
                        if (data.role.toLowerCase() === 'admin') {
                            window.location.href = 'admin.html';
                        } else if (data.role.toLowerCase() === 'student') {
                            window.location.href = 'student.html';
                        } else {
                            errorMessageDiv.textContent = '未知的用户角色。';
                            showLoginToast('未知的用户角色。', 'error');
                            // 恢复按钮状态
                            loginButton.disabled = false;
                            loginButton.innerHTML = originalButtonText;
                        }
                    }, 1000); // 1秒后跳转
                } else {
                    // 处理错误响应
                    errorMessageDiv.textContent = data.message || '登录失败，请检查用户名和密码。';
                    showLoginToast(data.message || '登录失败，请检查用户名和密码。', 'error');
                    // 恢复按钮状态
                    loginButton.disabled = false;
                    loginButton.innerHTML = originalButtonText;
                }
            } catch (error) {
                console.error('登录请求失败:', error);
                errorMessageDiv.textContent = '登录请求失败，请稍后重试。';
                showLoginToast('登录请求失败，请稍后重试。', 'error');
                // 恢复按钮状态
                loginButton.disabled = false;
                loginButton.innerHTML = originalButtonText;
            }
        });
    }
}); 